<?php
class Student
{
    private $surname;
    private $first_name;
    private $emails;
    private $grades=array();
    private $status;

    function __construct($surname, $first_name, $status)
    {
        $this->surname = $surname;
        $this->first_name = $first_name;
        $this->status = $status;
        $this->emails = array();
        $this->grades = array();
    }

    function add_email($which, $address)
    {
        $this->emails[$which] = $address;
    }
    function add_grade(Course $course ,$grade)
    {
        $this->grades[] = array(
            'course' => $course,
            'grade' => $grade
        );
    }

    function average()
    {
        $total = 0;
        $count = count($this->grades);
        if ($count === 0) return 0; 
        
        foreach ($this->grades as $item) {
            $total += $item['grade'];
        }
        return $total / $count;
    }

    function toString()
    {
        $result = $this->first_name . ' ' . $this->surname;
        $result .= ' (' . number_format($this->average(), 1) . ")";
        $result .= ' (' . $this->status . ")\n";
        foreach ($this->emails as $which => $what)
            $result .= $which . ': ' . $what . "\n";
        $result .= "\n";

        $gradeInfo = "Grades: ";
        foreach ($this->grades as $item) {
            $course = $item['course'];
            $grade = $item['grade'];
            $gradeInfo .= sprintf("%s(%s): %d分, ", 
                $course->getName() ?? '未命名课程', 
                $course->getCode() ?? '无代码', 
                $grade);
        }
        $gradeInfo = rtrim($gradeInfo, ", ") . "\n"; // 移除末尾逗号
        $result .= $gradeInfo . "\n";

        return '<pre>' . $result . '</pre>'; // 移至此处，确保所有信息都被包含
    }
}